﻿using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using System;
using Engine;
using System.Linq;

namespace Game.Plugin.MyShopPlugin
{
    public static class MyShopData
    {
        public static string ConfigFilePath { get; set; }
        public static Dictionary<string, MyShopListData> MyShopListDatas = new Dictionary<string, MyShopListData>();
        public static string _currentWorldName;
        private static bool _isDataDirty;
        private static object _dataLock = new object();

        // 玩家编辑模式状态
        public static Dictionary<string, bool> PlayerEditMode = new Dictionary<string, bool>();
        public static Dictionary<string, bool> PlayerViewMode = new Dictionary<string, bool>();
        public static Dictionary<string, ShopConfigMode> PlayerConfigMode = new Dictionary<string, ShopConfigMode>();
        public static Dictionary<string, bool> PlayerDeleteMode = new Dictionary<string, bool>();

        // 黑市数据
        public static List<BlackMarketItem> BlackMarketItems = new List<BlackMarketItem>();
        public static string BlackMarketFilePath => Storage.GetSystemPath("app:/PluginData/MoneyCoreApi/BlackMarket.json");
        private static int _nextItemId = 1;

        // 玩家操作冷却时间
        public static Dictionary<string, long> PlayerCooldowns = new Dictionary<string, long>();

        public static void Initialize()
        {
            if (string.IsNullOrEmpty(ConfigFilePath))
                throw new InvalidOperationException("ConfigFilePath 必须被正确设置.");
            string directory = Path.GetDirectoryName(ConfigFilePath);
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);
            LoadData();
            LoadBlackMarketData();
        }

        private static bool _isDataLoadedSuccessfully = false;
        public static void LoadData()
        {
            try
            {
                if (File.Exists(ConfigFilePath))
                {
                    using (StreamReader streamReader = File.OpenText(ConfigFilePath))
                    {
                        string value = streamReader.ReadToEnd();
                        Console.WriteLine("加载玩家金钱数据文件内容：");
                        Console.WriteLine(value);
                        MyShopListDatas = JsonConvert.DeserializeObject<Dictionary<string, MyShopListData>>(value);
                        if (MyShopListDatas == null)
                        {
                            Console.WriteLine("加载玩家金钱数据失败，文件内容可能为空或格式不正确。");
                            MyShopListDatas = new Dictionary<string, MyShopListData>();
                        }
                    }
                }
                else
                {
                    Console.WriteLine("玩家金钱数据文件不存在，将创建默认数据。");
                    MyShopListDatas = new Dictionary<string, MyShopListData>();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载商店数据时出错: {ex.Message}");
                MyShopListDatas = new Dictionary<string, MyShopListData>();
                _isDataLoadedSuccessfully = false;
            }
        }

        public static void LoadBlackMarketData()
        {
            try
            {
                if (File.Exists(BlackMarketFilePath))
                {
                    using (StreamReader streamReader = File.OpenText(BlackMarketFilePath))
                    {
                        string value = streamReader.ReadToEnd();
                        BlackMarketItems = JsonConvert.DeserializeObject<List<BlackMarketItem>>(value) ?? new List<BlackMarketItem>();

                        // 计算下一个可用的物品ID
                        if (BlackMarketItems.Count > 0)
                        {
                            _nextItemId = BlackMarketItems.Max(item => item.ItemId) + 1;
                        }
                        else
                        {
                            _nextItemId = 1;
                        }
                    }
                }
                else
                {
                    BlackMarketItems = new List<BlackMarketItem>();
                    SaveBlackMarketData();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载黑市数据时出错: {ex.Message}");
                BlackMarketItems = new List<BlackMarketItem>();
            }
        }

        public static void SaveData()
        {
            try
            {
                lock (_dataLock)
                {
                    string value = JsonConvert.SerializeObject(MyShopListDatas);
                    using (FileStream stream = File.Open(ConfigFilePath, FileMode.Create))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(stream))
                        {
                            streamWriter.Write(value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error($"保存玩家金钱数据失败：{ex.Message}");
            }
        }

        public static void SaveBlackMarketData()
        {
            try
            {
                string directory = Path.GetDirectoryName(BlackMarketFilePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string value = JsonConvert.SerializeObject(BlackMarketItems, Formatting.Indented);
                File.WriteAllText(BlackMarketFilePath, value);
            }
            catch (Exception ex)
            {
                Log.Error($"保存黑市数据失败：{ex.Message}");
            }
        }

        public static MyShopListData GetDataByGuid(string playerGuid)
        {
            if (MyShopListDatas.ContainsKey(playerGuid))
            {
                return MyShopListDatas[playerGuid];
            }
            return null;
        }

        public static void SetMyShopListDataByGuid(string playerGuid, MyShopListData newData)
        {
            lock (_dataLock)
            {
                if (MyShopListDatas.ContainsKey(playerGuid))
                {
                    MyShopListDatas[playerGuid] = newData;
                }
                else
                {
                    MyShopListDatas.Add(playerGuid, newData);
                }
                _isDataDirty = true;
            }
        }

        // 保留旧方法用于兼容性（但不再使用玩家名作为键）
        public static MyShopListData GetData(string playerName)
        {
            // 遍历查找匹配玩家名的数据
            foreach (var kvp in MyShopListDatas)
            {
                if (kvp.Value.playerName == playerName)
                {
                    return kvp.Value;
                }
            }
            return null;
        }

        public static void SetMyShopListData(string playerName, MyShopListData newData)
        {
            // 查找对应的GUID
            string playerGuid = null;
            foreach (var kvp in MyShopListDatas)
            {
                if (kvp.Value.playerName == playerName)
                {
                    playerGuid = kvp.Key;
                    break;
                }
            }

            if (playerGuid != null)
            {
                SetMyShopListDataByGuid(playerGuid, newData);
            }
        }

        public static void CreateDefaultConfig(string configFilePath)
        {
            try
            {
                string directory = Path.GetDirectoryName(ConfigFilePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                MyShopListDatas = new Dictionary<string, MyShopListData>();
                string json = JsonConvert.SerializeObject(MyShopListDatas, Formatting.Indented);
                File.WriteAllText(ConfigFilePath, json);

                Console.WriteLine("已创建MyShopListData默认配置文件");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"创建默认配置文件时出错: {ex.Message}");
            }
        }

        // 设置玩家编辑模式
        public static void SetPlayerEditMode(string playerGuid, bool enabled)
        {
            if (enabled)
            {
                PlayerEditMode[playerGuid] = true;
            }
            else
            {
                PlayerEditMode.Remove(playerGuid);
            }
        }

        // 设置玩家查看模式
        public static void SetPlayerViewMode(string playerGuid, bool enabled)
        {
            if (enabled)
            {
                PlayerViewMode[playerGuid] = true;
            }
            else
            {
                PlayerViewMode.Remove(playerGuid);
            }
        }

        // 设置玩家配置模式
        public static void SetPlayerConfigMode(string playerGuid, ShopConfigMode mode)
        {
            if (mode == null)
            {
                PlayerConfigMode.Remove(playerGuid);
            }
            else
            {
                PlayerConfigMode[playerGuid] = mode;
            }
        }

        // 设置玩家删除模式
        public static void SetPlayerDeleteMode(string playerGuid, bool enabled)
        {
            if (enabled)
            {
                PlayerDeleteMode[playerGuid] = true;
            }
            else
            {
                PlayerDeleteMode.Remove(playerGuid);
            }
        }

        // 获取玩家是否在编辑模式
        public static bool IsPlayerInEditMode(string playerGuid)
        {
            return PlayerEditMode.ContainsKey(playerGuid) && PlayerEditMode[playerGuid];
        }

        // 获取玩家是否在查看模式
        public static bool IsPlayerInViewMode(string playerGuid)
        {
            return PlayerViewMode.ContainsKey(playerGuid) && PlayerViewMode[playerGuid];
        }

        // 获取玩家是否在删除模式
        public static bool IsPlayerInDeleteMode(string playerGuid)
        {
            return PlayerDeleteMode.ContainsKey(playerGuid) && PlayerDeleteMode[playerGuid];
        }

        // 获取玩家配置模式
        public static ShopConfigMode GetPlayerConfigMode(string playerGuid)
        {
            if (PlayerConfigMode.ContainsKey(playerGuid))
            {
                return PlayerConfigMode[playerGuid];
            }
            return null;
        }

        // 检查玩家操作冷却时间
        public static bool CheckCooldown(string playerGuid, int cooldownSeconds = 1)
        {
            long currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            if (PlayerCooldowns.ContainsKey(playerGuid))
            {
                long lastTime = PlayerCooldowns[playerGuid];
                if (currentTime - lastTime < cooldownSeconds * 1000)
                {
                    return false;
                }
            }
            PlayerCooldowns[playerGuid] = currentTime;
            return true;
        }

        // 添加黑市物品
        public static bool AddBlackMarketItem(string playerGuid, string playerName, int contentItemId, int price, int count)
        {
            // 检查玩家上架物品数量限制（最多3个）
            int playerItemCount = BlackMarketItems.Count(item => item.SellerGuid == playerGuid);
            if (playerItemCount >= 3)
            {
                return false;
            }

            // 创建新的黑市物品
            BlackMarketItem newItem = new BlackMarketItem
            {
                ItemId = _nextItemId,
                SellerGuid = playerGuid,
                SellerName = playerName,
                ContentItemId = contentItemId,
                Price = price,
                Count = count,
                CreateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            };

            BlackMarketItems.Add(newItem);
            _nextItemId++;
            SaveBlackMarketData();
            return true;
        }

        // 获取黑市物品列表
        public static List<BlackMarketItem> GetBlackMarketItems()
        {
            return new List<BlackMarketItem>(BlackMarketItems);
        }

        // 根据序号获取黑市物品
        public static BlackMarketItem GetBlackMarketItemById(int itemId)
        {
            return BlackMarketItems.FirstOrDefault(item => item.ItemId == itemId);
        }

        // 购买黑市物品
        public static bool BuyBlackMarketItem(string buyerGuid, int itemId, out BlackMarketItem item)
        {
            item = GetBlackMarketItemById(itemId);
            if (item != null)
            {
                if (item.SellerGuid == buyerGuid)
                {
                    item = null;
                    return false; // 不能购买自己的物品
                }

                BlackMarketItems.Remove(item);
                SaveBlackMarketData();
                return true;
            }
            return false;
        }
    }

    // 商店配置模式类
    public class ShopConfigMode
    {
        public string shopName;
        public string shopType;
        public int itemId;
        public int count;
        public double money;
        public bool isActive;
    }

    // 黑市物品类
    public class BlackMarketItem
    {
        public int ItemId { get; set; } // 黑市物品序号
        public string SellerGuid { get; set; }
        public string SellerName { get; set; }
        public int ContentItemId { get; set; } // 实际物品ID
        public int Price { get; set; }
        public int Count { get; set; }
        public long CreateTime { get; set; }
    }
}